const express = require('express');
const router = express.Router();

const cartModule=require('../database/module/cartModule');
const BVOModule=require('../database/module/bvoModule');
const productModule = require('../database/module/productModule');
//将商品添加到购物车、创建购物车
router.all('/addToCart',(req,res)=>{
    cartModule.create(req.body).then(data=>{
        res.send(true);
    }).catch(err=>{
        console.log(err);
        res.send(false);
    })
})
//编辑购物车商品数量
router.all('/editInCart',(req,res)=>{
    cartModule.updateOne({$and:[{bvo_id:req.body.bov_id},{product_id:req.body.bov_id}]},{amount:req.body.amount}).then(data=>{
        res.send(true)
    }).catch(err=>{
        console.log(err);
        res.send(false);
    })
})

async function getProductDetail(cart_data, ret) {
    let i;
    for(i=0;i<cart_data.length;i++) {
        let e = cart_data[i]
        await productModule.findOne({_id:e.product_id}).then(product => {
            const obj = {
                bvo_id: e.bvo_id,
                amount: e.amount,
                product_id: e.product_id,
                name: product.name,
                price: product.price,
                description: product.description,
                category: product.category,
                image_url: product.image_url,
                stock: product.stock,
                rating: product.rating
            };
            ret.push(obj);
        })
    }
}

//获取购物车信息
router.all('/getFromCart',(req,res)=>{
        //return [{bvo_id, amount, product_id, name, price, description, category, image_url, stock, rating}]
    let ret = [];
    cartModule.find({bvo_id:req.body.bvo_id}).then(cart_data=>{
        getProductDetail(cart_data, ret).then(() => {
            res.send(ret);
        })
    })
    
})
//从购物车删除商品
router.all('/deleteFromCart',(req,res)=>{
    cartModule.deleteOne({$and:[{bvo_id:req.body.bvo_id},{product_id:req.body.product_id}]}).then(data=>{
        res.send(true);
    }).catch(err=>{
        console.log(err);
        res.send(false)
    })
})
module.exports=router;